//
//  LocalizableManager.swift
//  MultiLanguage
//
//  Created by macvivi on 2022/3/20.- (NSString *)localizedStringForKey:(NSString *)key value:(nullable NSString *)value table:(nullable NSString *)tableName;
//

import UIKit

enum LanguageType {
    case chinese,english,auto
}


class LocalizableManager: NSObject {
    
    static func localValue(_ str:String) -> String {
        LocalizableManager.shared.localValue(str: str)
    }
    
    static func setLanguage(_ type:LanguageType){
        LocalizableManager.shared.setLanguage(type)
    }
    
    
    //单例
    static let shared = LocalizableManager()
    
     private override init() {
        
    }
    
    var bundle:Bundle = Bundle.main
    
    private func localValue(str:String) -> String{
        //table参数值传nil也是可以的，传nil系统就会默认为Localizable
        bundle.localizedString(forKey: str, value: nil, table: "Localizable")
    }
    

    
    private func setLanguage(_ type:LanguageType){
        var typeStr = ""
        switch type {
        case .chinese:
            typeStr = "zh-Hans"
            UserDefaults.standard.setValue("zh-Hans", forKey: "language")
        case .english:
            typeStr = "en"
            UserDefaults.standard.setValue("en", forKey: "language")
        default:
            break
        }
        //返回项目中 en.lproj 文件的路径
        let path = Bundle.main.path(forResource: typeStr, ofType: "lproj")
        //用这个路径生成新的bundle
        bundle = Bundle(path: path!)!
        if type == .auto {
            //和系统语言一致
            bundle = Bundle.main
            UserDefaults.standard.removeObject(forKey: "language")
        }
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: "languageChanged"), object: nil)
    }

}
